﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;

namespace Phoenix.Xna.Framework.Xml
{
    public class XmlStreamer
    {
        private static XmlReaderSettings _settings;

        static XmlStreamer()
        {
            _settings = new XmlReaderSettings();
            _settings.ConformanceLevel = ConformanceLevel.Fragment;
        }

        public static List<XElement> Read(string path)
        {
            List<XElement> elements = new List<XElement>();
            IEnumerable<XElement> data = from el in StreamElements(path)
                                         select (XElement)el;

            foreach (XElement e in data)
            {
                elements.Add(e);
            }

            return elements;
        }

        private static IEnumerable<XElement> StreamElements(string path)
        {
            using (Stream fileStream = new FileStream(path, FileMode.Open))
            {
                using (XmlReader reader = XmlReader.Create(fileStream, _settings))
                {
                    while (reader.Read())
                    {
                        if (reader.NodeType == XmlNodeType.Element)
                        {
                            XElement element = (XElement)XElement.ReadFrom(reader);

                            if (element != null)
                            {
                                yield return element;
                            }
                        }
                    }

                    reader.Close();
                }

                fileStream.Close();
            }
        }
    }
}
